package org.ns.summer.data.mybatis;

import org.ns.summer.aop.MethodInterceptor;
import org.ns.summer.aop.MethodInvoke;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MybatisTransactionProxy implements MethodInterceptor {
    private Map<Method, Transaction> methods = new HashMap<>();
    // Logger log = LoggerFactory.getLogger(getClass());
    public MybatisTransactionProxy(Map<Method, Transaction> methods) {
        this.methods = methods;
    }

    @Override
    public Object invoke(MethodInvoke methodInvoke) throws Throwable {
        Method method = methodInvoke.getMethod();

        if (methods.containsKey(method)) {
            Transaction transaction = methods.get(method);
            // 创建事务管理
            MybatisTransactionManage manage =
                    MybatisTransactionManage.create(method, transaction.executortype(), transaction.autoJta());

            try {
                Object result = methodInvoke.proceed();
                manage.commit(method);
                return result;
            } catch (Throwable e) {
                manage.rollback(method);
                throw e;
            } finally {
                manage.close(method);
            }
        }
        return methodInvoke.proceedProxy();
    }


}
